import type { AnyObject } from "antd/es/_util/type";
import { useCallback, useEffect, useState } from "react";

type Props = {
  AMap: typeof AMap | undefined | null,
  map: AMap.Map | null | undefined
}

const nationFill = 'rgba(8, 119, 198, 0.5)';



const useInitWorld = ({ AMap, map }: Props) => {

  const [data, setData] = useState<string>('')


  // 初始化国家图层并绑定点击事件
  const initDisWorld = useCallback(() => {
    if (!AMap || !map) return
    setData('CHN')
    const disWorld = new AMap.DistrictLayer.World({
      zIndex: 10,
      styles: {
        'fill': function (_: AnyObject) {
          if (_.SOC == 'CHN') {
            // updateInfo(props);
            return nationFill;
          }
          // else {
          //   return 'white'
          // }
        },
      }
    });
    // map.setLayers([disWorld])
    disWorld.setMap(map)

    map.on('click', function (ev: AMap.MapsEvent) {

      const px = ev.pixel;
      // 拾取所在位置的行政区
      const props = disWorld.getDistrictByContainerPos(px);

      if (props) {
        const SOC = props.SOC;
        setData(SOC)
        if (SOC) {
          // 重置行政区样式
          disWorld.setStyles({
            'fill': function (props: AnyObject) {
              return props.SOC == SOC ? nationFill : '';
            }
          });
          // updateInfo(props);
        }
      }
    });
  }, [AMap, map])





  useEffect(() => {
    initDisWorld()
  }, [initDisWorld])



  return {
    countryCode: data
  }
}

export default useInitWorld